package com.zack.serversocket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;

import com.zack.util.DataTransfer;
import com.zack.util.ServerUtil;

public class ClientService implements Runnable{
	
	private Socket socket;
	
	ObjectInputStream in = null;
	ObjectOutputStream out = null;
	
	ClientService(Socket socket){
		
		this.socket = socket;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		try {
			in =new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
			ServerUtil.addInToMap(socket.getPort(), in);
			out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
			ServerUtil.addOutToMap(socket.getPort(), out);
			while(true) {	
				if(!socket.isClosed()) {
					DataTransfer dt = (DataTransfer) in.readObject();
					String msg = dt.getContent();
					if ("bye".equals(msg)) { 
		                break;  
		            }
					dt.setIsSuccess(true);
					System.out.println("客户端"+dt.getName()+"说:"+msg);
					out.writeObject(dt);
					//out.write(null);
					out.flush();
					for(Socket otherClient : ServerUtil.getClientList()) {
						if(!socket.equals(otherClient)) {
							ObjectOutputStream mass = ServerUtil.getOutByPort(otherClient.getPort());
							DataTransfer outDT = new DataTransfer();
							outDT.setName(dt.getName());
							outDT.setContent(dt.getContent());
							mass.writeObject(dt);
							mass.flush();
						}
						
						
					}
					
				}
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				ServerUtil.removenClientInfo(socket);
				if(in!= null) {
					in.close();
				}
				if(out!= null) {
					out.close();
				}
				if(socket!= null) {
				    socket.close();
				}
				
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
